import datetime
import json
import os
import uuid
from functools import wraps
from jwt import decode as jwt_decode
from django.contrib.auth.decorators import login_required
from django.db.models import Sum, DateField, Avg, F, Q, Count
from django.db.models.functions import TruncYear, TruncMonth, Extract, TruncDay
from django.forms import model_to_dict
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.utils import timezone
import requests
from auth_app.models import User
from django_it_community import settings
from it_app.models import Type, Article, Follow, Collect, Notice, Message


# 定义装饰器，在请求前判断是否为超级管理员
def is_superuser(func):
    @wraps(func)
    def wrapper(request, *args, **kwargs):
        if request.user.id is None or User.objects.get(id=request.user.id).is_superuser is False:
            return JsonResponse({"code": 9, "msg": "No permission"})
        return func(request, *args, **kwargs)

    return wrapper


# -------------------------管理端-分类管理---------------------------------------

@is_superuser
@login_required
def typelist(request):
    if request.method == 'GET':
        return render(request, 'typelist.html')
    elif request.method == 'POST':
        try:
            rd = json.loads(request.body)
            qs = Type.objects.filter(name__contains=rd['name'])
            total = qs.count()
            qs = qs[(rd['page_index'] - 1) * rd['page_size']:(rd['page_index']) * rd['page_size']]
            res_data = [model_to_dict(i) for i in qs]
            return JsonResponse({"code": 0, "msg": "", "data": {"data": res_data, "total": total}})
        except Exception as e:
            print(e)
            return JsonResponse({"code": 9, "msg": str(e), "data": {}})


@is_superuser
@login_required
def add_type(request):
    try:
        rd = json.loads(request.body)
        ma = Type.objects.create(
            name=rd.get('name'),
            description=rd.get('description'),
        )
        ma.save()
        return JsonResponse({"code": 0, "msg": "创建成功", "data": {}})
    except Exception as e:
        print(e)
        return JsonResponse({"code": 9, "msg": str(e), "data": {}})


@is_superuser
@login_required
def update_type(request):
    try:
        rd = json.loads(request.body)
        Type.objects.filter(id=rd.get('id')).update(**rd)
        return JsonResponse({"code": 0, "msg": "更新成功", "data": {}})
    except Exception as e:
        return JsonResponse({"code": 9, "msg": str(e), "data": {}})


@is_superuser
@login_required
def delete_type(request):
    try:
        rd = json.loads(request.body)
        Type.objects.filter(id__in=rd['idlist']).delete()
        return JsonResponse({"code": 0, "msg": "删除成功", "data": {}})
    except Exception as e:
        return JsonResponse({"code": 9, "msg": str(e), "data": {}})


# -------------------------管理端-公告管理---------------------------------------

@is_superuser
@login_required
def noticelist(request):
    if request.method == 'GET':
        return render(request, 'noticelist.html')
    elif request.method == 'POST':
        try:
            rd = json.loads(request.body)
            qs = Notice.objects.filter(title__contains=rd['title'], content__contains=rd['content'])
            total = qs.count()
            qs = qs[(rd['page_index'] - 1) * rd['page_size']:(rd['page_index']) * rd['page_size']]
            res_data = [{
                **model_to_dict(i),
                "update_time": i.update_time.strftime("%Y-%m-%d %H:%M:%S")
            } for i in qs]
            return JsonResponse({"code": 0, "msg": "", "data": {"data": res_data, "total": total}})
        except Exception as e:
            print(e)
            return JsonResponse({"code": 9, "msg": str(e), "data": {}})


@is_superuser
@login_required
def add_notice(request):
    try:
        rd = json.loads(request.body)
        ma = Notice.objects.create(
            title=rd.get('title'),
            content=rd.get('content'),
        )
        ma.save()
        return JsonResponse({"code": 0, "msg": "创建成功", "data": {}})
    except Exception as e:
        print(e)
        return JsonResponse({"code": 9, "msg": str(e), "data": {}})


@is_superuser
@login_required
def update_notice(request):
    try:
        rd = json.loads(request.body)
        Notice.objects.filter(id=rd.get('id')).update(**rd)
        return JsonResponse({"code": 0, "msg": "更新成功", "data": {}})
    except Exception as e:
        return JsonResponse({"code": 9, "msg": str(e), "data": {}})


@is_superuser
@login_required
def delete_notice(request):
    try:
        rd = json.loads(request.body)
        Notice.objects.filter(id__in=rd['idlist']).delete()
        return JsonResponse({"code": 0, "msg": "删除成功", "data": {}})
    except Exception as e:
        return JsonResponse({"code": 9, "msg": str(e), "data": {}})


# -------------------------管理端-系统消息管理---------------------------------------

@is_superuser
@login_required
def messagelist(request):
    if request.method == 'GET':
        userlist = User.objects.all()
        return render(request, 'messagelist.html', {"userlist": [{"id": i.id, "username": i.first_name} for i in userlist]})
    elif request.method == 'POST':
        try:
            rd = json.loads(request.body)
            qs = Message.objects.filter(user__first_name__contains=rd['username'])
            total = qs.count()
            qs = qs[(rd['page_index'] - 1) * rd['page_size']:(rd['page_index']) * rd['page_size']]
            res_data = [{
                "id": i.id,
                "user_id": i.user_id,
                "username": i.user.first_name,
                "content": i.content,
                "create_time": i.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                "title": i.title,
                "is_read": i.is_read,
            } for i in qs]
            return JsonResponse({"code": 0, "msg": "", "data": {"data": res_data, "total": total}})
        except Exception as e:
            return JsonResponse({"code": 9, "msg": str(e), "data": {}})


@is_superuser
@login_required
def add_message(request):
    try:
        rd = json.loads(request.body)
        ma = Message.objects.create(
            title=rd.get('title'),
            content=rd.get('content'),
            user_id=rd.get('user_id'),
        )
        ma.save()
        return JsonResponse({"code": 0, "msg": "创建成功", "data": {}})
    except Exception as e:
        print(e)
        return JsonResponse({"code": 9, "msg": str(e), "data": {}})


@is_superuser
@login_required
def update_message(request):
    try:
        rd = json.loads(request.body)
        Message.objects.filter(id=rd.get('id')).update(**rd)
        return JsonResponse({"code": 0, "msg": "更新成功", "data": {}})
    except Exception as e:
        return JsonResponse({"code": 9, "msg": str(e), "data": {}})


@is_superuser
@login_required
def delete_message(request):
    try:
        rd = json.loads(request.body)
        Message.objects.filter(id__in=rd['idlist']).delete()
        return JsonResponse({"code": 0, "msg": "删除成功", "data": {}})
    except Exception as e:
        return JsonResponse({"code": 9, "msg": str(e), "data": {}})


# -------------------------管理端-用户管理---------------------------------------
@login_required
@is_superuser
def userlist(request):
    if request.method == 'GET':
        return render(request, 'userlist.html')
    elif request.method == 'POST':
        try:
            rd = json.loads(request.body)
            qs = User.objects.filter(first_name__contains=rd['first_name'])
            total = qs.count()
            qs = qs[(rd['page_index'] - 1) * rd['page_size']:(rd['page_index']) * rd['page_size']]
            res_data = [{
                "id": i.id,
                "username": i.username,
                "first_name": i.first_name,
                "is_active": i.is_active,
                "email": i.email,
                "phone": i.phone,
                "ava": i.ava,
                "is_superuser": 1 if i.is_superuser else 2,
                "sex": i.sex,
            } for i in qs]
            return JsonResponse({"code": 0, "msg": "", "data": {"data": res_data, "total": total}})
        except Exception as e:
            return JsonResponse({"code": 9, "msg": str(e), "data": {}})


@login_required
@is_superuser
def add_user(request):
    if request.method == 'POST':
        try:
            rd = json.loads(request.body)
            if User.objects.filter(username=rd['username']).exists():
                return JsonResponse({"code": 9, "msg": "该账号已被注册", "data": {}})
            else:
                qs = User.objects.create(
                    username=rd.get('username'),
                    first_name=rd.get('first_name'),
                    sex=rd.get('sex'),
                    phone=rd.get('phone'),
                    is_superuser=True if rd.get('is_superuser') == 1 else False,
                    email=rd.get('email'),
                )
                if rd.get('password') != "":
                    qs.set_password(rd.get('password'))
                else:
                    qs.set_password('123')
                return JsonResponse({"code": 0, "msg": "创建成功", "data": {}})
        except Exception as e:
            return JsonResponse({"code": 9, "msg": str(e), "data": {}})


@login_required
@is_superuser
def update_user(request):
    if request.method == 'POST':
        try:
            rd = json.loads(request.body)
            user = User.objects.get(id=rd.get('id'))
            user.first_name = rd.get('first_name')
            user.sex = rd.get('sex')
            user.phone = rd.get('phone')
            user.type = rd.get('type')
            user.username = rd.get('username')
            user.email = rd.get('email')
            user.is_superuser = True if rd.get('is_superuser') == 1 else False
            if rd.get("password") != "":
                user.set_password(rd.get("password"))
            user.save()
            return JsonResponse({"code": 0, "msg": "更新成功", "data": {}})
        except Exception as e:
            return JsonResponse({"code": 9, "msg": str(e), "data": {}})


@login_required
@is_superuser
def delete_user(request):
    if request.method == 'POST':
        try:
            rd = json.loads(request.body)
            User.objects.exclude(username='admin').filter(id__in=rd.get('idlist')).delete()
            return JsonResponse({"code": 0, "msg": "删除成功", "data": {}})
        except Exception as e:
            return JsonResponse({"code": 9, "msg": str(e), "data": {}})


@login_required
@is_superuser
def articlelist(request):
    if request.method == 'GET':
        return render(request, 'articlelist.html')
    elif request.method == 'POST':
        try:
            rd = json.loads(request.body)
            qs = Article.objects.filter(
                user__first_name__contains=rd['first_name'],
                title__contains=rd['title'],
                rang=1,
                status=1
            )
            total = qs.count()
            qs = qs[(rd['page_index'] - 1) * rd['page_size']:(rd['page_index']) * rd['page_size']]
            res_data = [{
                **model_to_dict(i),
                "user": i.user.first_name,
                "type": i.type.name
            } for i in qs]
            return JsonResponse({"code": 0, "msg": "", "data": {"data": res_data, "total": total}})
        except Exception as e:
            return JsonResponse({"code": 9, "msg": str(e), "data": {}})


@login_required
@is_superuser
def update_articlelist(request):
    if request.method == 'POST':
        try:
            rd = json.loads(request.body)
            art = Article.objects.get(id=rd.get('id'))
            art.examine = rd.get('examine')
            art.save()
            return JsonResponse({"code": 0, "msg": "更新成功", "data": {}})
        except Exception as e:
            return JsonResponse({"code": 9, "msg": str(e), "data": {}})


@login_required
@is_superuser
def delete_articlelist(request):
    if request.method == 'POST':
        try:
            rd = json.loads(request.body)
            print(rd)
            qs = Article.objects.filter(id__in=rd.get('idlist'))
            for i in qs:
                if i.cover:
                    os.remove('static/source/%s' % i.cover)
            qs.delete()
            return JsonResponse({"code": 0, "msg": "删除成功", "data": {}})
        except Exception as e:
            print(e)
            return JsonResponse({"code": 9, "msg": "删除失败：" + str(e), "data": {}})